<template>
  <div class="simple-pdf-viewer">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <h2>📄 PDF预览器</h2>
          <p class="subtitle">支持PDF文件上传、预览和下载</p>
        </div>
      </template>
      
      <!-- 文件上传区域 -->
      <div class="upload-section">
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :show-file-list="false"
          accept=".pdf"
          :on-change="handleFileChange"
          drag
          class="upload-dragger"
        >
          <div class="upload-content">
            <el-icon class="upload-icon"><Upload /></el-icon>
            <div class="upload-text">
              <p class="upload-title">点击或拖拽PDF文件到此处</p>
              <p class="upload-hint">支持PDF格式文件，最大10MB</p>
            </div>
          </div>
        </el-upload>
      </div>
      
      <!-- 调试信息 -->
      <div v-if="showDebug" class="debug-info">
        <h4>🔍 调试信息</h4>
        <div class="debug-grid">
          <div class="debug-item">
            <span class="label">Loading:</span>
            <span class="value" :class="{ 'loading': loading }">{{ loading }}</span>
          </div>
          <div class="debug-item">
            <span class="label">Error:</span>
            <span class="value error">{{ error || '无' }}</span>
          </div>
          <div class="debug-item">
            <span class="label">PDF URL:</span>
            <span class="value">{{ pdfUrl ? '已设置' : '未设置' }}</span>
          </div>
          <div class="debug-item">
            <span class="label">Visible Pages:</span>
            <span class="value">{{ visiblePages.join(', ') || '无' }}</span>
          </div>
        </div>
        <el-button @click="showDebug = !showDebug" size="small" type="info">
          隐藏调试信息
        </el-button>
      </div>
      
      <!-- 调试按钮 -->
      <div v-if="!showDebug" class="debug-toggle">
        <el-button @click="showDebug = true" size="small" type="info">
          显示调试信息
        </el-button>
      </div>
      
      <!-- PDF预览区域 -->
      <div v-if="pdfUrl" class="pdf-preview-section">
        <div class="preview-header">
          <h3>📖 PDF预览</h3>
          <div class="preview-actions">
            <el-button @click="downloadPdf" type="primary" :icon="Download">
              下载PDF
            </el-button>
            <el-button @click="clearPdf" type="danger" :icon="Delete">
              清除
            </el-button>
          </div>
        </div>
        
        <!-- PDF控制栏 -->
        <div v-if="totalPages > 0" class="pdf-controls">
          <div class="page-controls">
            <el-button @click="previousPage" :disabled="currentPage <= 1" size="small">
              上一页
            </el-button>
            <span class="page-info">
              第 {{ currentPage }} 页，共 {{ totalPages }} 页
              <span v-if="isRendering" class="rendering-indicator">🔄 渲染中...</span>
            </span>
            <el-button @click="nextPage" :disabled="currentPage >= totalPages" size="small">
              下一页
            </el-button>
          </div>
          
          <div class="scale-controls">
            <el-button @click="zoomOut" size="small" :disabled="autoFit">缩小</el-button>
            <span class="scale-info">{{ autoFit ? '自适应' : Math.round(scale * 100) + '%' }}</span>
            <el-button @click="zoomIn" size="small" :disabled="autoFit">放大</el-button>
            <el-button @click="toggleAutoFit" size="small" :type="autoFit ? 'primary' : 'default'">
              {{ autoFit ? '关闭自适应' : '开启自适应' }}
            </el-button>
            <el-button @click="refreshPdf" size="small" type="warning" :disabled="isRendering">
              刷新渲染
            </el-button>
            <el-button @click="debugTextContent" size="small" type="info" :disabled="isRendering">
              调试文字
            </el-button>
            <el-button @click="performOCR" size="small" type="warning" :disabled="isRendering || ocrLoading" :loading="ocrLoading">
              OCR识别
            </el-button>
            <el-button @click="performSimpleOCR" size="small" type="success" :disabled="isRendering || ocrLoading" :loading="ocrLoading">
              简单识别
            </el-button>
          </div>
        </div>
        
        <div class="canvas-container">
          <!-- 测试Canvas -->
          <div class="canvas-item test-canvas">
            <h4>🧪 测试Canvas</h4>
            <canvas 
              id="test-canvas" 
              width="400" 
              height="600"
              class="canvas-element test"
            ></canvas>
            <p class="canvas-label">用于测试DOM渲染</p>
          </div>
          
          <!-- PDF Canvas -->
          <div v-for="pageNum in visiblePages" :key="pageNum" class="canvas-item pdf-canvas">
            <h4>📄 页面 {{ pageNum }}</h4>
            <canvas 
              :id="`pdf-canvas-${pageNum}`"
              width="400" 
              height="600"
              class="canvas-element pdf"
            ></canvas>
            <p class="canvas-label">PDF内容将在这里渲染</p>
            
            <!-- 文字显示说明 -->
            <div class="text-display-notice">
              <p><strong>注意：</strong>PDF文字显示说明：</p>
              <ul>
                <li>PDF内容已正常渲染，文字层渲染已禁用以避免乱码</li>
                <li>如果PDF是扫描版，请使用"OCR识别"功能提取文字</li>
                <li>如果PDF有文字但显示异常，请使用"简单识别"分析</li>
              </ul>
              <p>请使用"OCR识别"或"简单识别"按钮来提取文字内容</p>
            </div>
            
            <!-- OCR识别结果 -->
            <div v-if="ocrText" class="ocr-result">
              <h4>🔍 OCR识别结果：</h4>
              <div class="ocr-text-content">
                <pre>{{ ocrText }}</pre>
              </div>
              <div class="ocr-actions">
                <el-button @click="copyOcrText" size="small" type="primary">
                  <el-icon><CopyDocument /></el-icon>
                  复制文字
                </el-button>
                <el-button @click="ocrText = ''" size="small" type="info">
                  <el-icon><Close /></el-icon>
                  清除结果
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload, Download, Delete } from '@element-plus/icons-vue'

const loading = ref(false)
const error = ref('')
const pdfUrl = ref('')
const visiblePages = ref<number[]>([])
const showDebug = ref(false)
const uploadRef = ref()
const currentPage = ref(1)
const totalPages = ref(0)
const scale = ref(1.0)
const pdfDocument = ref<any>(null)
const autoFit = ref(true)
const isRendering = ref(false)
const ocrLoading = ref(false)
const ocrText = ref('')

const handleFileChange = async (file: any) => {
  if (!file || !file.raw) return
  
  console.log('🎯 SimplePdfViewer - 文件选择:', file.name)
  
  try {
    loading.value = true
    error.value = ''
    
    const url = URL.createObjectURL(file.raw)
    pdfUrl.value = url
    
    // 设置可见页面
    visiblePages.value = [1]
    
    console.log('🎯 SimplePdfViewer - 设置visiblePages:', visiblePages.value)
    
    // 等待DOM更新
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 检查canvas
    const testCanvas = document.getElementById('test-canvas')
    console.log('🎯 SimplePdfViewer - 测试Canvas:', testCanvas)
    
    const allCanvases = document.querySelectorAll('canvas')
    console.log('🎯 SimplePdfViewer - 所有Canvas:', Array.from(allCanvases).map(c => c.id))
    
    const pdfCanvas = document.getElementById('pdf-canvas-1')
    console.log('🎯 SimplePdfViewer - PDF Canvas:', pdfCanvas)
    
    // 在测试canvas上画一些内容
    if (testCanvas) {
      const ctx = testCanvas.getContext('2d')
      if (ctx) {
        ctx.fillStyle = '#e74c3c'
        ctx.fillRect(10, 10, 100, 50)
        ctx.fillStyle = 'white'
        ctx.font = '16px Arial'
        ctx.fillText('测试Canvas', 15, 35)
        console.log('🎯 SimplePdfViewer - 测试Canvas已绘制内容')
      }
    }
    
    // 尝试渲染PDF
    await renderPdfToCanvas(pdfCanvas, url)
    
    ElMessage.success('PDF文件加载成功！')
    
  } catch (err) {
    error.value = '文件处理失败: ' + (err as Error).message
    ElMessage.error('文件处理失败')
  } finally {
    loading.value = false
  }
}

const downloadPdf = () => {
  if (pdfUrl.value) {
    const link = document.createElement('a')
    link.href = pdfUrl.value
    link.download = 'document.pdf'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    ElMessage.success('PDF下载开始')
  }
}

const clearPdf = () => {
  pdfUrl.value = ''
  visiblePages.value = []
  error.value = ''
  currentPage.value = 1
  totalPages.value = 0
  scale.value = 1.0
  pdfDocument.value = null
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
  ElMessage.info('已清除PDF文件')
}

// 翻页功能
const previousPage = async () => {
  if (currentPage.value > 1 && !isRendering.value) {
    currentPage.value--
    await renderCurrentPage()
  }
}

const nextPage = async () => {
  if (currentPage.value < totalPages.value && !isRendering.value) {
    currentPage.value++
    await renderCurrentPage()
  }
}

// 缩放功能
const zoomIn = async () => {
  if (!isRendering.value) {
    scale.value = Math.min(scale.value + 0.25, 3.0)
    await renderCurrentPage()
  }
}

const zoomOut = async () => {
  if (!isRendering.value) {
    scale.value = Math.max(scale.value - 0.25, 0.5)
    await renderCurrentPage()
  }
}

// 切换自适应缩放
const toggleAutoFit = async () => {
  if (!isRendering.value) {
    autoFit.value = !autoFit.value
    if (autoFit.value) {
      ElMessage.info('已开启自适应缩放')
    } else {
      ElMessage.info('已关闭自适应缩放')
    }
    await renderCurrentPage()
  }
}

// 刷新PDF渲染
const refreshPdf = async () => {
  if (!isRendering.value && pdfUrl.value) {
    ElMessage.info('正在刷新PDF渲染...')
    
    // 清除当前PDF文档
    pdfDocument.value = null
    
    // 重新加载PDF
    const canvas = document.getElementById('pdf-canvas-1') as HTMLCanvasElement
    if (canvas) {
      await renderPdfToCanvas(canvas, pdfUrl.value)
    }
  }
}

// OCR识别功能
const performOCR = async () => {
  if (!pdfDocument.value) {
    ElMessage.warning('请先加载PDF文件')
    return
  }
  
  ocrLoading.value = true
  ocrText.value = ''
  
  try {
    console.log('🎯 SimplePdfViewer - 开始OCR识别')
    
    // 获取当前页面的Canvas
    const canvas = document.getElementById('pdf-canvas-1') as HTMLCanvasElement
    if (!canvas) {
      ElMessage.error('无法找到PDF Canvas')
      return
    }
    
    // 将Canvas转换为图片
    const imageData = canvas.toDataURL('image/png')
    
    // 动态导入Tesseract.js
    const { createWorker } = await import('tesseract.js')
    
    // 创建OCR工作器，使用本地化配置
    const worker = await createWorker('chi_sim+eng', 1, {
      logger: m => {
        if (m.status === 'recognizing text') {
          console.log(`OCR进度: ${Math.round(m.progress * 100)}%`)
        }
      },
      // 使用本地worker文件避免CSP问题
      workerPath: '/tesseract/worker.min.js',
      langPath: 'https://tessdata.projectnaptha.com/4.0.0/',
      corePath: '/tesseract/tesseract-core.wasm.js'
    })
    
    // 执行OCR识别
    const { data: { text } } = await worker.recognize(imageData)
    
    // 清理工作器
    await worker.terminate()
    
    ocrText.value = text
    console.log('🎯 SimplePdfViewer - OCR识别完成:', text)
    
    if (text.trim()) {
      ElMessage.success(`OCR识别完成，识别到 ${text.length} 个字符`)
    } else {
      ElMessage.warning('OCR未识别到文字内容')
    }
    
  } catch (err) {
    console.error('🎯 SimplePdfViewer - OCR识别失败:', err)
    
    // 如果OCR失败，提供备用方案
    try {
      console.log('🎯 SimplePdfViewer - 尝试备用OCR方案')
      
      // 使用更简单的配置
      const { createWorker } = await import('tesseract.js')
      const worker = await createWorker('eng', 1, {
        logger: m => {
          if (m.status === 'recognizing text') {
            console.log(`备用OCR进度: ${Math.round(m.progress * 100)}%`)
          }
        }
      })
      
      const canvas = document.getElementById('pdf-canvas-1') as HTMLCanvasElement
      const imageData = canvas.toDataURL('image/png')
      const { data: { text } } = await worker.recognize(imageData)
      
      await worker.terminate()
      
      ocrText.value = text
      if (text.trim()) {
        ElMessage.success(`备用OCR识别完成，识别到 ${text.length} 个字符`)
      } else {
        ElMessage.warning('备用OCR也未识别到文字内容')
      }
      
    } catch (backupErr) {
      console.error('🎯 SimplePdfViewer - 备用OCR也失败:', backupErr)
      ElMessage.error('OCR识别失败，请检查网络连接或尝试其他PDF文件')
    }
  } finally {
    ocrLoading.value = false
  }
}

// 简单OCR识别（使用浏览器内置API）
const performSimpleOCR = async () => {
  if (!pdfDocument.value) {
    ElMessage.warning('请先加载PDF文件')
    return
  }
  
  ocrLoading.value = true
  ocrText.value = ''
  
  try {
    console.log('🎯 SimplePdfViewer - 开始简单OCR识别')
    
    // 获取当前页面的Canvas
    const canvas = document.getElementById('pdf-canvas-1') as HTMLCanvasElement
    if (!canvas) {
      ElMessage.error('无法找到PDF Canvas')
      return
    }
    
    // 将Canvas转换为图片
    const imageData = canvas.toDataURL('image/png')
    
    // 创建一个临时的img元素
    const img = new Image()
    img.src = imageData
    
    // 等待图片加载
    await new Promise((resolve, reject) => {
      img.onload = resolve
      img.onerror = reject
    })
    
    // 使用Canvas API进行简单的文字识别
    // 这里我们只是提取一些基本信息
    const ctx = canvas.getContext('2d')
    if (!ctx) {
      throw new Error('无法获取Canvas上下文')
    }
    
    // 获取Canvas的像素数据
    const imageData2 = ctx.getImageData(0, 0, canvas.width, canvas.height)
    const data = imageData2.data
    
    // 简单的文字检测（基于像素分析）
    let textInfo = '简单识别结果：\n'
    textInfo += `图片尺寸: ${canvas.width} x ${canvas.height}\n`
    textInfo += `像素总数: ${data.length / 4}\n`
    
    // 分析像素分布
    let darkPixels = 0
    let lightPixels = 0
    for (let i = 0; i < data.length; i += 4) {
      const r = data[i]
      const g = data[i + 1]
      const b = data[i + 2]
      const brightness = (r + g + b) / 3
      if (brightness < 128) {
        darkPixels++
      } else {
        lightPixels++
      }
    }
    
    textInfo += `深色像素: ${darkPixels}\n`
    textInfo += `浅色像素: ${lightPixels}\n`
    textInfo += `对比度: ${(darkPixels / (darkPixels + lightPixels) * 100).toFixed(2)}%\n`
    
    // 检测可能的文字区域
    const textRegions = detectTextRegions(data, canvas.width, canvas.height)
    textInfo += `检测到 ${textRegions.length} 个可能的文字区域\n`
    
    ocrText.value = textInfo
    ElMessage.success('简单识别完成')
    
  } catch (err) {
    console.error('🎯 SimplePdfViewer - 简单OCR识别失败:', err)
    ElMessage.error('简单识别失败')
  } finally {
    ocrLoading.value = false
  }
}

// 检测文字区域的简单算法
const detectTextRegions = (data: Uint8ClampedArray, width: number, height: number) => {
  const regions: Array<{x: number, y: number, w: number, h: number}> = []
  const visited = new Array(width * height).fill(false)
  
  for (let y = 0; y < height; y += 10) {
    for (let x = 0; x < width; x += 10) {
      const index = (y * width + x) * 4
      if (visited[y * width + x]) continue
      
      const r = data[index]
      const g = data[index + 1]
      const b = data[index + 2]
      const brightness = (r + g + b) / 3
      
      // 如果像素足够暗，可能是文字
      if (brightness < 100) {
        const region = floodFill(data, visited, x, y, width, height)
        if (region.w > 5 && region.h > 5) {
          regions.push(region)
        }
      }
    }
  }
  
  return regions
}

// 洪水填充算法
const floodFill = (data: Uint8ClampedArray, visited: boolean[], startX: number, startY: number, width: number, height: number) => {
  const stack = [{x: startX, y: startY}]
  let minX = startX, maxX = startX, minY = startY, maxY = startY
  
  while (stack.length > 0) {
    const {x, y} = stack.pop()!
    if (x < 0 || x >= width || y < 0 || y >= height || visited[y * width + x]) continue
    
    const index = (y * width + x) * 4
    const r = data[index]
    const g = data[index + 1]
    const b = data[index + 2]
    const brightness = (r + g + b) / 3
    
    if (brightness >= 100) continue
    
    visited[y * width + x] = true
    minX = Math.min(minX, x)
    maxX = Math.max(maxX, x)
    minY = Math.min(minY, y)
    maxY = Math.max(maxY, y)
    
    // 添加相邻像素
    stack.push({x: x + 1, y}, {x: x - 1, y}, {x, y: y + 1}, {x, y: y - 1})
  }
  
  return {x: minX, y: minY, w: maxX - minX, h: maxY - minY}
}

// 复制OCR文字
const copyOcrText = async () => {
  try {
    await navigator.clipboard.writeText(ocrText.value)
    ElMessage.success('文字已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage.error('复制失败')
  }
}

// 调试文字内容
const debugTextContent = async () => {
  if (!pdfDocument.value) {
    ElMessage.warning('请先加载PDF文件')
    return
  }
  
  try {
    console.log('🎯 SimplePdfViewer - 调试文字内容:')
    
    // 方法1：直接使用现有的PDF文档对象
    try {
      const page = await pdfDocument.value.getPage(currentPage.value)
      const textContent = await page.getTextContent()
      console.log('方法1 - 使用现有PDF对象，文字项数:', textContent.items.length)
      
      if (textContent.items.length > 0) {
        let allText = ''
        textContent.items.forEach((item: any, index: number) => {
          if (item.str) {
            allText += item.str + ' '
            if (index < 20) { // 显示前20个文字项
              console.log(`文字项 ${index}:`, item.str, item.transform)
            }
          }
        })
        console.log('所有文字内容:', allText)
        ElMessage.success(`找到 ${textContent.items.length} 个文字项，文字内容已显示在控制台`)
        return
      }
    } catch (err) {
      console.log('方法1失败:', err)
    }
    
    // 方法2：重新加载PDF文档
    const pdfjsLib = (window as any).pdfjsLib
    const loadingTask = pdfjsLib.getDocument({
      url: pdfUrl.value,
      cMapUrl: 'https://unpkg.com/pdfjs-dist@3.11.174/cmaps/',
      cMapPacked: true,
      standardFontDataUrl: 'https://unpkg.com/pdfjs-dist@3.11.174/standard_fonts/',
      disableFontFace: false,
      disableRange: false,
      disableStream: false,
      disableAutoFetch: false,
      useSystemFonts: true,
      verbosity: 1
    })
    
    const pdf = await loadingTask.promise
    const page = await pdf.getPage(currentPage.value)
    
    const textContent = await page.getTextContent()
    console.log('方法2 - 重新加载PDF，文字项数:', textContent.items.length)
    
    // 显示前20个文字项
    let allText = ''
    textContent.items.forEach((item: any, index: number) => {
      if (item.str) {
        allText += item.str + ' '
        if (index < 20) { // 显示前20个文字项
          console.log(`文字项 ${index}:`, item.str, item.transform)
        }
      }
    })
    
    console.log('所有文字内容:', allText)
    
    if (textContent.items.length === 0) {
      ElMessage.warning('PDF中可能没有可提取的文字内容（可能是扫描版PDF）')
    } else {
      ElMessage.success(`找到 ${textContent.items.length} 个文字项，文字内容已显示在控制台`)
    }
    
  } catch (err) {
    console.error('🎯 SimplePdfViewer - 调试文字内容失败:', err)
    ElMessage.error('调试文字内容失败')
  }
}

// 计算自适应缩放比例
const calculateAutoScale = (page: any, containerWidth: number) => {
  const viewport = page.getViewport({ scale: 1.0 })
  const scaleX = containerWidth / viewport.width
  return Math.min(scaleX, 2.0) // 最大2倍缩放
}

// 渲染当前页
const renderCurrentPage = async () => {
  if (!pdfDocument.value || isRendering.value) return
  
  const canvas = document.getElementById('pdf-canvas-1') as HTMLCanvasElement
  if (!canvas) return
  
  isRendering.value = true
  
  try {
    // 重新获取页面，避免PDF文档对象失效
    const page = await pdfDocument.value.getPage(currentPage.value)
    
    // 计算实际缩放比例
    let actualScale = scale.value
    if (autoFit.value) {
      const containerWidth = canvas.parentElement?.clientWidth || 800
      actualScale = calculateAutoScale(page, containerWidth - 40) // 减去边距
    }
    
    const viewport = page.getViewport({ scale: actualScale })
    console.log('🎯 SimplePdfViewer - 实际缩放比例:', actualScale, '视口尺寸:', viewport.width, 'x', viewport.height)
    
    // 获取设备像素比
    const devicePixelRatio = window.devicePixelRatio || 1
    
    // 设置canvas实际尺寸（考虑设备像素比）
    canvas.width = viewport.width * devicePixelRatio
    canvas.height = viewport.height * devicePixelRatio
    
    // 设置canvas显示尺寸
    canvas.style.width = viewport.width + 'px'
    canvas.style.height = viewport.height + 'px'
    
    // 缩放canvas上下文以匹配设备像素比
    const context = canvas.getContext('2d')
    if (context) {
      context.scale(devicePixelRatio, devicePixelRatio)
    }
    
    // 渲染页面（简化配置）
    const renderContext = {
      canvasContext: canvas.getContext('2d'),
      viewport: viewport,
      // 禁用文字层渲染，避免乱码问题
      renderInteractiveForms: false,
      enableWebGL: false
    }
    
    await page.render(renderContext).promise
    console.log(`🎯 SimplePdfViewer - 渲染第${currentPage.value}页完成，缩放: ${Math.round(actualScale * 100)}%`)
    
    // 暂时禁用文字层渲染，避免乱码和覆盖问题
    console.log('🎯 SimplePdfViewer - 跳过文字层渲染，避免乱码问题')
    
  } catch (err) {
    console.error('🎯 SimplePdfViewer - 渲染页面失败:', err)
    
    // 如果渲染失败，尝试重新加载PDF
    if (pdfUrl.value) {
      console.log('🎯 SimplePdfViewer - 尝试重新加载PDF')
      await renderPdfToCanvas(canvas, pdfUrl.value)
    }
  } finally {
    isRendering.value = false
  }
}

// PDF渲染函数
const renderPdfToCanvas = async (canvas: HTMLCanvasElement | null, pdfUrl: string) => {
  if (!canvas) {
    console.log('🎯 SimplePdfViewer - Canvas为空，无法渲染PDF')
    return
  }
  
  try {
    console.log('🎯 SimplePdfViewer - 开始渲染PDF到Canvas')
    
    // 检查PDF.js是否可用
    if (typeof window !== 'undefined' && (window as any).pdfjsLib) {
      const pdfjsLib = (window as any).pdfjsLib
      console.log('🎯 SimplePdfViewer - PDF.js库可用')
      
      // 配置PDF.js
      pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js'
      
      // 加载PDF文档（尝试不同的配置来提取文字）
      const loadingTask = pdfjsLib.getDocument({
        url: pdfUrl,
        disableFontFace: false,
        disableRange: false,
        disableStream: false,
        disableAutoFetch: false,
        useSystemFonts: true,
        verbosity: 1,
        // 尝试强制启用文字提取
        cMapUrl: 'https://unpkg.com/pdfjs-dist@3.11.174/cmaps/',
        cMapPacked: true,
        standardFontDataUrl: 'https://unpkg.com/pdfjs-dist@3.11.174/standard_fonts/'
      })
      const pdf = await loadingTask.promise
      console.log('🎯 SimplePdfViewer - PDF文档加载成功，页数:', pdf.numPages)
      
      // 保存PDF文档引用
      pdfDocument.value = pdf
      totalPages.value = pdf.numPages
      currentPage.value = 1
      
      // 渲染第一页
      const page = await pdf.getPage(1)
      console.log('🎯 SimplePdfViewer - 获取第1页成功')
      
      // 计算实际缩放比例
      let actualScale = scale.value
      if (autoFit.value) {
        const containerWidth = canvas.parentElement?.clientWidth || 800
        actualScale = calculateAutoScale(page, containerWidth - 40) // 减去边距
      }
      
      const viewport = page.getViewport({ scale: actualScale })
      console.log('🎯 SimplePdfViewer - 实际缩放比例:', actualScale, '视口尺寸:', viewport.width, 'x', viewport.height)
      
      // 获取设备像素比
      const devicePixelRatio = window.devicePixelRatio || 1
      console.log('🎯 SimplePdfViewer - 设备像素比:', devicePixelRatio)
      
      // 设置canvas实际尺寸（考虑设备像素比）
      canvas.width = viewport.width * devicePixelRatio
      canvas.height = viewport.height * devicePixelRatio
      
      // 设置canvas显示尺寸
      canvas.style.width = viewport.width + 'px'
      canvas.style.height = viewport.height + 'px'
      
      // 缩放canvas上下文以匹配设备像素比
      const context = canvas.getContext('2d')
      if (context) {
        context.scale(devicePixelRatio, devicePixelRatio)
      }
      
      // 渲染页面（简化配置）
      const renderContext = {
        canvasContext: canvas.getContext('2d'),
        viewport: viewport,
        // 禁用文字层渲染，避免乱码问题
        renderInteractiveForms: false,
        enableWebGL: false
      }
      
      await page.render(renderContext).promise
      console.log('🎯 SimplePdfViewer - PDF页面渲染完成')
      
      // 暂时禁用文字层渲染，避免乱码和覆盖问题
      console.log('🎯 SimplePdfViewer - 跳过文字层渲染，避免乱码问题')
      
    } else {
      console.log('🎯 SimplePdfViewer - PDF.js库不可用，绘制占位内容')
      
      // 绘制占位内容
      const ctx = canvas.getContext('2d')
      if (ctx) {
        ctx.fillStyle = '#3498db'
        ctx.fillRect(0, 0, canvas.width, canvas.height)
        ctx.fillStyle = 'white'
        ctx.font = '24px Arial'
        ctx.textAlign = 'center'
        ctx.fillText('PDF内容将在这里显示', canvas.width / 2, canvas.height / 2)
        ctx.fillText('(PDF.js库未加载)', canvas.width / 2, canvas.height / 2 + 30)
      }
    }
    
  } catch (err) {
    console.error('🎯 SimplePdfViewer - PDF渲染失败:', err)
    
    // 绘制错误信息
    const ctx = canvas.getContext('2d')
    if (ctx) {
      ctx.fillStyle = '#e74c3c'
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      ctx.fillStyle = 'white'
      ctx.font = '18px Arial'
      ctx.textAlign = 'center'
      ctx.fillText('PDF渲染失败', canvas.width / 2, canvas.height / 2)
      ctx.fillText((err as Error).message, canvas.width / 2, canvas.height / 2 + 30)
    }
  }
}

// 预加载字体
const preloadFonts = () => {
  const fonts = [
    'Arial', 'Helvetica', 'Times New Roman', 'Courier New',
    'Microsoft YaHei', 'SimSun', 'SimHei', 'KaiTi', 'FangSong'
  ]
  
  fonts.forEach(font => {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    if (ctx) {
      ctx.font = `12px ${font}`
      ctx.fillText('测试', 0, 0)
    }
  })
  
  console.log('🎯 SimplePdfViewer - 字体预加载完成')
}

// 组件挂载时的测试
onMounted(() => {
  console.log('🎯 SimplePdfViewer - 组件已挂载')
  
  // 预加载字体
  preloadFonts()
  
  // 等待DOM渲染完成
  setTimeout(() => {
    const testCanvas = document.getElementById('test-canvas')
    console.log('🎯 SimplePdfViewer - 挂载后测试Canvas:', testCanvas)
    
    const allCanvases = document.querySelectorAll('canvas')
    console.log('🎯 SimplePdfViewer - 挂载后所有Canvas:', Array.from(allCanvases).map(c => c.id))
    
    if (testCanvas) {
      const ctx = testCanvas.getContext('2d')
      if (ctx) {
        ctx.fillStyle = '#27ae60'
        ctx.fillRect(10, 10, 100, 50)
        ctx.fillStyle = 'white'
        ctx.font = '16px Arial'
        ctx.fillText('组件已挂载', 15, 35)
        console.log('🎯 SimplePdfViewer - 挂载时测试Canvas已绘制')
      }
    }
  }, 100)
})
</script>

<style scoped>
.simple-pdf-viewer {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.main-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  overflow: hidden;
}

.card-header {
  text-align: center;
  padding: 10px 0;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
}

.subtitle {
  margin: 0;
  color: #7f8c8d;
  font-size: 16px;
}

.upload-section {
  margin: 30px 0;
}

.upload-dragger {
  width: 100%;
}

.upload-content {
  padding: 40px 20px;
  text-align: center;
}

.upload-icon {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 20px;
}

.upload-title {
  font-size: 18px;
  color: #2c3e50;
  margin: 0 0 8px 0;
  font-weight: 500;
}

.upload-hint {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.debug-info {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 1px solid #dee2e6;
  border-radius: 8px;
  padding: 20px;
  margin: 20px 0;
}

.debug-info h4 {
  margin: 0 0 15px 0;
  color: #495057;
  font-size: 16px;
}

.debug-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 15px;
}

.debug-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.debug-item .label {
  font-weight: 500;
  color: #495057;
}

.debug-item .value {
  color: #6c757d;
  font-family: monospace;
  font-size: 13px;
}

.debug-item .value.loading {
  color: #fd7e14;
  font-weight: 600;
}

.debug-item .value.error {
  color: #dc3545;
  font-weight: 600;
}

.debug-toggle {
  text-align: center;
  margin: 20px 0;
}

.pdf-preview-section {
  margin-top: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #e9ecef;
}

.preview-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 20px;
}

.preview-actions {
  display: flex;
  gap: 10px;
}

.pdf-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
}

.page-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-info {
  font-weight: 500;
  color: #495057;
  min-width: 120px;
  text-align: center;
}

.rendering-indicator {
  color: #409eff;
  font-size: 12px;
  margin-left: 8px;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.scale-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.scale-info {
  font-weight: 500;
  color: #495057;
  min-width: 60px;
  text-align: center;
}

.canvas-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.canvas-item {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.canvas-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.canvas-item h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  font-size: 16px;
}

.canvas-element {
  display: block;
  margin: 0 auto 15px auto;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  max-width: 100%;
  height: auto;
  image-rendering: -webkit-optimize-contrast;
  image-rendering: crisp-edges;
}

.canvas-element.test {
  border: 3px solid #e74c3c;
  background: #fdf2f2;
}

.canvas-element.pdf {
  border: 3px solid #3498db;
  background: #f0f8ff;
}

.canvas-label {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
  font-style: italic;
}

.text-display-notice {
  margin-top: 15px;
  padding: 15px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  font-size: 13px;
  color: #495057;
}

.text-display-notice p {
  margin: 0 0 10px 0;
}

.text-display-notice ul {
  margin: 10px 0;
  padding-left: 20px;
}

.text-display-notice li {
  margin: 5px 0;
}

.ocr-result {
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 8px;
  padding: 16px;
  margin-top: 16px;
}

.ocr-result h4 {
  margin: 0 0 12px 0;
  color: #856404;
  font-size: 16px;
}

.ocr-text-content {
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 12px;
  max-height: 200px;
  overflow-y: auto;
}

.ocr-text-content pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.4;
  color: #333;
}

.ocr-actions {
  display: flex;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .simple-pdf-viewer {
    padding: 10px;
  }
  
  .card-header h2 {
    font-size: 24px;
  }
  
  .preview-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .preview-actions {
    justify-content: center;
  }
  
  .canvas-container {
    grid-template-columns: 1fr;
  }
  
  .canvas-element {
    width: 100%;
    max-width: 300px;
    height: auto;
  }
}
</style>
